﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CashFlow.Repository;
using System.Diagnostics.Contracts;
using CashFlow.Entities;
using CashFlow.Common;

namespace CashFlow.AzureRepository
{
	public class AzureAppIdentityRepository : AzureRepositoryBase, IAppIdentityRepository
	{
		#region Table operations
		public string GetTenantId(string provider, string name)
		{
			Contract.Requires(!string.IsNullOrEmpty(provider), "Provider cannot be null.");
			Contract.Requires(!string.IsNullOrEmpty(name), "Name cannot be null.");

			string result = null;
			var dbEntity = GetByKeys<AzureAppIdentity>(Constants.TableNames.AppIdentities, provider, name);
			//TODO: vvs p3 this check can be moved to the base class (it will be done for all tables).
			if (dbEntity != null)
			{
				result = dbEntity.TenantId;
			}

			return result;
		}

		public void Create(AppIdentity identity)
		{
			Contract.Requires(identity != null, "Identity cannot be null.");

			//TODO: vvs p2 save with retry.
			var azureEntity = (AzureAppIdentity)identity;
			db.AddObject(Constants.TableNames.AppIdentities, azureEntity);
			db.SaveChanges();
		}
		#endregion
	}
}
